package org.celery.modules.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import lombok.AllArgsConstructor;
import org.celery.modules.goods.entity.Goods;
import org.celery.modules.goods.entity.GoodsStyle;
import org.celery.modules.goods.vo.GoodsVO;
import org.celery.modules.goods.mapper.GoodsMapper;
import org.celery.modules.goods.service.IGoodsService;
import org.celery.modules.order.entity.Order;
import org.springblade.common.cache.CacheNames;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.RedisUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * 商品表 服务实现类
 *
 * @author Celery
 * @since 2021-10-26
 */
@Service
@AllArgsConstructor
public class GoodsServiceImpl extends BaseServiceImpl<GoodsMapper, Goods> implements IGoodsService {

	private RedisUtil redisUtil;

	@Override
	public IPage<GoodsVO> selectGoodsPage(IPage<GoodsVO> page, GoodsVO goods) {
		return page.setRecords(baseMapper.selectGoodsPage(page, goods));
	}

	@Override
	public List<String> getCategoryName(String categoryIds) {
		return baseMapper.getCategoryName(Func.toStrArray(categoryIds));
	}

	@Transactional
	@Override
	public boolean addSell(Order order) {
		List<GoodsStyle> goodsStyleList = JsonUtil.parseArray(order.getAssociatedGoods(), GoodsStyle.class);

		for (GoodsStyle goodsStyle : goodsStyleList) {
			Goods goods = baseMapper.selectById(goodsStyle.getGoodsId());
			goods.setSell(goods.getSell() + 1);
			goods.setDisplaySell(goods.getDisplaySell() + 1);
			baseMapper.updateById(goods);
		}

		return true;
	}

	@Override
	public Goods getById(Serializable id) {
		Object goodsObject = redisUtil.get(CacheNames.GOODS_INSTANCE + id);
		Goods goods = Func.isNotEmpty(goodsObject) ? (Goods) goodsObject : null;
		if (Func.isEmpty(goods)) {
			goods = super.getById(id);
			if (Func.isNotEmpty(goods)) {
				redisUtil.set(CacheNames.GOODS_INSTANCE + id, goods);
			}
		}
		return goods;
	}

	@Override
	public boolean saveOrUpdate(Goods entity) {
		boolean isTrue = super.saveOrUpdate(entity);
		Goods goods = (Goods) redisUtil.get(CacheNames.GOODS_INSTANCE + entity.getId());
		if (Func.isNotEmpty(goods)) {
			redisUtil.del(CacheNames.GOODS_INSTANCE + entity.getId());
		}
		return isTrue;
	}
}
